#pragma once
#include <iostream>
#include <cstdio>
#include <string>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <unistd.h>
using namespace std;
const string pathname = ".";
const int gdefaultid = -1;
const int gsize = 4096;
const int projid = 0x66;
#define CREATER "creater"
#define USER "user"
#define ERR_EXIT(m)         \
    do                      \
    {                       \
        perror(m);          \
        exit(EXIT_FAILURE); \
    } while (0)

class Shm
{
public:
    Shm(const string &pathname, int projid, const string &usertype)
        : _shmid(gdefaultid), _size(gsize), _start_mem(nullptr), _usertype(usertype)
    {
        _key = ftok(pathname.c_str(), projid);
        if (_key < 0)
        {
            ERR_EXIT("ftok\n");//获取key失败报错
        }
        printf("key: 0x%x\n", _key);
        if (_usertype == CREATER)
        {
            Create();
        }
        else if (_usertype == USER)
            Get();
        else
        {
        }
        Attach();
    }
    ~Shm() = default;
    // 打印映射的虚拟地址
    void *VirtualAddr()
    {
        printf("VirtualAddr: %p\n", _start_mem);
        return _start_mem;
    }
    int Size()
    {
        return _size;
    }
    //创建共享内存
    void Create()
    {
        _shmid = shmget(_key, _size, IPC_CREAT | IPC_EXCL | 0666);
        if (_shmid < 0)
        {
            ERR_EXIT("shmget\n");
        }
        printf("shmid : %d", _shmid);
    }
    //获取已经存在的共享内存
    void Get()
    {
        _shmid = shmget(_key, _size, IPC_CREAT |  0666);
        if (_shmid < 0)
        {
            ERR_EXIT("shmget\n");
        }
        printf("shmid : %d", _shmid);
    }
   
   
    //将共享内存映射到虚拟地址空间
    void Attach()
    {
        _start_mem = shmat(_shmid, nullptr, 0);
        if ((long long)_start_mem < 0)
        {
            ERR_EXIT("shmat");
        }
        printf("attach success\n");
    }
    //解除映射
    void Detach()
    {
        int n = shmdt(_start_mem);
        if (n == 0)
        {
            printf("detach success\n");
        }
    }
    //销毁共享内存
    void Destory()
    {
        
        Detach();
        if (_usertype == CREATER)
        {
            int n = shmctl(_shmid, IPC_RMID, nullptr);
            if (n > 0)
                printf("shmctl delete shm %d success\n", _shmid);
            else
                ERR_EXIT("shmctl");
        }
    }
    //打印共享内存的属性
    void Attr()
    {
        struct shmid_ds ds;
        int n = shmctl(_shmid, IPC_STAT, &ds);
        printf("shm_segsz: %ld\n", ds.shm_segsz);
        printf("key: 0x%x\n", ds.shm_perm.__key);
    }

private:
    int _shmid;        // 共享内存标识符
    key_t _key;        // 共享内存键值
    int _size;         // 共享内存大小
    void *_start_mem;  // 共享内存映射地址
    std::string _usertype;  // 用户类型（"creater"或"user"
};